package network;/*
 *@ 代阳敲的专属代码
 **/

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoService {
    private ServerSocket socket;
    // 这个操作就会绑定端⼝号
    public  TcpEchoService(int port) throws IOException {
        if(1024>port||port>65535) {
            throw new BindException("端口不合法");
        }
        this.socket=new ServerSocket(port);
    }
    // 启动服务器
    public void  start() throws IOException {
        System.out.println("服务器启动");
        while(true) {
            Socket clienSocket =socket.accept();
            ExecutorService service= Executors.newCachedThreadPool();
            service.submit(new Runnable() {
                   @Override
                   public void run() {
                       processConnection(clienSocket);
                   }
            });
        }
    }
//    public void  start() throws IOException {
//        System.out.println("服务器启动");
//        while(true) {
//            Socket clienSocket =socket.accept();
//            Thread t=new Thread(()->{
//                processConnection(clienSocket);
//            });
//            t.start();
//        }
//    }


    // 通过这个⽅法来处理⼀个连接的逻辑
    private void processConnection(Socket clienSocket) {
        System.out.printf("[%s:%d] 客户端上线！\n",clienSocket.getInetAddress().toString(),clienSocket.getPort());
        try {
            InputStream inputStream=clienSocket.getInputStream();
            OutputStream outputStream=clienSocket.getOutputStream();
            // ⼀次连接中, 可能会涉及到多次请求/响应
            while(true) {
                Scanner scanner=new Scanner(inputStream);
                if(!scanner.hasNext()) {
                    // 读取完毕, 客⼾端下线
                    System.out.printf("[%s:%d] 客⼾端下线!\n" ,clienSocket.getInetAddress(),clienSocket.getPort());
                    break;
                }
                //
                String request=scanner.next();
                // 2. 根据请求计算响应
                String response = process(request);
                //把数据返回给客户端，用Prwinter包裹一层
                PrintWriter writer=new PrintWriter(outputStream);
                writer.println(response);
                writer.flush();
                System.out.printf("[%s:%d] req: %s, resp: %s\n",
                        clienSocket.getInetAddress(),clienSocket.getPort(),request,response);

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            // 在 finally 中加上 close 操作, 确保当前 socket 被及时关闭!!
            try {
                clienSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoService server =new TcpEchoService(8080);
        server.start();
    }
}
